package com.aidansmeaton.weightmanager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.aidansmeaton.weightmanager.data.RedditPost;

/** The first activity in the app. */
public class ImageSearchActivity extends ListActivity implements OnItemClickListener {

	private List<RedditPost> posts;
	private RedditAdapter adapter;	

	private Context context;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inspiration);
		
		context = this;
		posts = new ArrayList<RedditPost>();
		
		DownloadPostsTask downloadTask = new DownloadPostsTask();
		downloadTask.execute(0);

	}
	
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		
		/*
		Intent postIntent = new Intent(this, InspirationPostActivity.class);		
		postIntent.putExtra("Title", posts.get(position).getTitle());
		postIntent.putExtra("Date", posts.get(position).getDate());
		postIntent.putExtra("Description", posts.get(position).getDescription());
		postIntent.putExtra("Link", posts.get(position).getLink().toString());
		startActivity(postIntent);
		*/
		
		RedditPost post = (RedditPost) view.getTag(R.id.reddit_post);
		Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(post.getLink().toString()));
		startActivity(browserIntent);
		
    }

	private void downloadPosts() {

		String htmlResult = "";
		InputStream is = null;

		// http post
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet("http://images.google.com/searchbyimage?image_url=weightmanager.clanteam.com%2Fuploads%2Fcola.jpg");
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}
		// convert response to string
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}

			is.close();

			htmlResult = sb.toString();
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		}
		
		Log.w("RESULT",htmlResult);

		/*
		while (htmlResult.contains("<item>")) {
			int itemStart = htmlResult.indexOf("<item>");
			int itemEnd = htmlResult.indexOf("</item>");

			String item = htmlResult.substring(itemStart, itemEnd + 7);

			String title = parseNextToken(item, "<title>", "</title>");
			String link = parseNextToken(item, "<link>", "</link>");
			String date = parseNextToken(item, "<pubDate>", "</pubDate>");
			String description = parseNextToken(item, "<description>", "</description>");

			URL linkURL = null;
			try {
				linkURL = new URL(link);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}

			RedditPost post = new RedditPost(title, linkURL, date, description);
			posts.add(post);
			htmlResult = htmlResult.substring(itemEnd + 7, htmlResult.length());
			Log.w("",""+htmlResult.length());
		}
		*/
	}

	private String parseNextToken(String fullText, String prefix, String suffix) {

		int itemStart = fullText.indexOf(prefix);
		int itemEnd = fullText.indexOf(suffix);

		return fullText.substring(itemStart + prefix.length(), itemEnd);
	}

	private class RedditAdapter extends ArrayAdapter<RedditPost> {

		private List<RedditPost> posts;

		public RedditAdapter(Context context, int textViewResourceId,
				List<RedditPost> posts) {
			super(context, textViewResourceId, posts);
			this.posts = posts;
		}

		@Override
		public int getCount() {
			return posts.size();
		}

		@Override
		public RedditPost getItem(int position) {
			return posts.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.reddit_row, null);
			}

			TextView titleTextView = (TextView) convertView.findViewById(R.id.reddit_row_title);
			TextView timeTextView = (TextView) convertView.findViewById(R.id.reddit_row_time);
			WebView description = (WebView) convertView.findViewById(R.id.web_engine);

			RedditPost post = posts.get(position);
			convertView.setTag(R.id.reddit_post, post);

			titleTextView.setText(Html.fromHtml(post.getTitle()));
			timeTextView.setText(post.getDate());
			
			description.getSettings().setJavaScriptEnabled(true); 
			String data = "<html><body>";
			data += Html.fromHtml(post.getDescription());
			data += "</body></html>";
			description.loadData(data, "text/html", "UTF-8");

			return convertView;
		}
	}
	
	
	/* AsyncTask to download posts. */
	private class DownloadPostsTask extends AsyncTask<Integer, Integer, Boolean> {
		
		ProgressDialog dialog;
		
		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(context);
			dialog.setTitle("Downloading Inspiration!");
			dialog.setMessage("Downloading posts from the /r/loseit online community.");
			dialog.setIndeterminate(true);
			dialog.setCancelable(false);
			dialog.show();
		}
		
		@Override
		protected Boolean doInBackground(Integer... args) {
			downloadPosts();
			return true;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			adapter = new RedditAdapter(ImageSearchActivity.this, R.layout.reddit_row, posts);
			setListAdapter(adapter);
			getListView().setOnItemClickListener(ImageSearchActivity.this);
			
			try {
				dialog.dismiss();
			} catch (IllegalArgumentException e) {
				/* See Ticket #11. Appears to throw this error
				 * if the dialog somehow loses its parent view.
				 * Can safely be ignored in this case, we're only
				 * hiding a dialog window.
				 */
			}
		}
	}
}